<script setup lang="ts" name="SystemUserImportForm">
import { UserApi } from '@/api/system/user'
import { dataToFile } from '@/components/Excel/src/helper'
import { isSuccess } from '@/utils/axios/helper'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const fileList: any = ref([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的用户数据

/** 打开弹窗 */
const open = () => {
  visible.value = true
  updateSupport.value = 0
  fileList.value = []
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error(t('sys.user.rules', 'emptyFile'))
    return
  }
  console.log(updateSupport.value)
  formLoading.value = true
  const resBody = new FormData()
  resBody.append('file', fileList.value[0].raw)
  resBody.append('updateSupport', updateSupport.value + '')
  const response = await UserApi.import(resBody)
  submitFormSuccess(response)
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (!isSuccess(response)) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  // 拼接提示语
  const data = response.data
  let text = t('sys.user.rules', 'createCount') + data.createUsernames.length + ';'
  for (let username of data.createUsernames) {
    text += '< ' + username + ' >'
  }
  text += t('sys.user.rules', 'updateCount') + data.updateUsernames.length + ';'
  for (const username of data.updateUsernames) {
    text += '< ' + username + ' >'
  }
  text += t('sys.user.rules', 'errorCount') + Object.keys(data.failureUsernames).length + ';'
  for (const username in data.failureUsernames) {
    text += '< ' + username + ': ' + data.failureUsernames[username] + ' >'
  }
  message.alert(text)
  formLoading.value = false
  visible.value = false
  // 发送操作成功的事件
  emits('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error(t('sys.user.rules', 'errorUpload'))
  formLoading.value = false
}

/** 重置表单 */
const resetForm = async (): Promise<void> => {
  // 重置上传状态和文件
  formLoading.value = false
  await nextTick()
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error(t('sys.user.rules', 'maxFileLen'))
}

/** 下载模板操作 */
const importTemplate = async () => {
  const options = {
    filename: `${t('sys.user', 'import')}.xlsx`,
    fileType: 'xlsx',
    dataScope: 3,
    header: {
      username: t('sys.user', 'username'),
      nickname: t('sys.user', 'nickname'),
      mobile: t('sys.user', 'mobile'),
      email: t('sys.user', 'email'),
      sex: t('sys.user', 'sex'),
    },
    sort: ['username', 'nickname', 'mobile', 'email', 'sex'],
    headerType: 'custom'
  }
  const res = [{ username: 'xxxxxx', nickname: 'xxx', mobile: 'xxxxxxxxxxx', email: 'xxx@xxx.xxx', sex: 'x' }]
  dataToFile(res, options)
}
</script>

<template>
  <Dialog v-model="visible" :title="t('sys.user', 'importTitle')" width="400">
    <el-upload ref="uploadRef" v-model:file-list="fileList" action="" :auto-upload="false" :disabled="formLoading" :limit="1" :on-error="submitFormError" :on-exceed="handleExceed" accept=".xlsx, .xls" drag>
      <SvgIcon icon="ep:upload" size="24" />
      <div class="el-upload__text mt-10px">
        {{ t('sys.user', 'guide') }}<em>{{ t('sys.user', 'upload') }}</em>
      </div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip flex items-center justify-center">
            <el-checkbox v-model="updateSupport" class="!mr-6px" />
            {{ t('sys.user', 'tips') }}
          </div>
          <span>{{ t('sys.user', 'accept') }}</span>
          <el-link :underline="false" style="font-size: 12px; vertical-align: baseline" type="primary" @click="importTemplate"> {{ t('sys.user', 'download') }} </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button @click="visible = false">{{ t('action', 'cancel') }}</el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">{{ t('action', 'confirm') }}</el-button>
    </template>
  </Dialog>
</template>

<style scoped lang="scss"></style>
